//
//  EFBaseViewController.m
//  EFHealth
//
//  Created by liumadu on 14-11-28.
//  Copyright (c) 2018年 ef. All rights reserved.
//
//#import "LoginModelHandler.h"
//#import "EFLoginModel.h"

#import "EFBaseViewController.h"

#import "EFNavigationController.h"
#import "LoginViewController.h"   //登录界面

#import "MBProgressHUD.h"
#import "EFNoDataView.h"
//#import "EFProgressHUD.h"
#import "EFApiConst.h"
#import "AppDelegate.h"

// 获取当前设备可用内存及所占内存的头文件
#import <sys/sysctl.h>
#import <mach/mach.h>

@interface EFBaseViewController ()<MBProgressHUDDelegate/*,LoginModelProtocol*/,UIAlertViewDelegate>
{
    allertMessageCallback _alertMessageCancel ;
    allertMessageCallback _alertMessageSure ;
}
//@property (nonatomic,strong)EFLoginModel     *loginModel ;
//@property (nonatomic,strong)LoginModelHandler*loginHandler ;

@property (nonatomic, strong) MBProgressHUD *hud;// 提示框
@property (nonatomic, strong) EFNoDataView *nodataView ;//没有数据，无网络提示

@property (nonatomic, strong)EFNavigationBarView *navBarView ;//导航条

@property (nonatomic,strong)NSMutableString *APPCacheCollectStr ;

@end

@implementation EFBaseViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (_navBarView && !_navBarView.hidden) {
        [self.view bringSubviewToFront:_navBarView];
    }
    if (DEBUG_Development) {
//        [self showMemoryView];
    }
}

- (void)bringNavBarToTopmost
{
    if (_navBarView) {
        [self.view bringSubviewToFront:_navBarView];
    }
}
- (void)navigationDragCanBack:(BOOL)canBack
{
    if (self.navigationController) {
        self.navigationController.interactivePopGestureRecognizer.enabled = canBack;
    }
}

- (void)dealloc
{
//    if (DEBUG_Development) {
//        NSInteger aa = App_delegate.tabbar.selectedViewController.childViewControllers.count;
//        EFLog(@"===================%@销毁%p__%ld",[self class],self,aa);
//    }
}
- (void)viewDidLoad
{
    
    if (DEBUG_Development) {
        EFLog(@"===================%@创建%p",[self class],self);
    }
    
    [super viewDidLoad];
    [self initModel];
    [self initView];
}

- (EFNavigationBarView *)navBarView
{
    if (nil == _navBarView) {
        _navBarView = [[EFNavigationBarView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, KNavFullHeight)];
        _navBarView.controlVC = self ;
        [self.view addSubview:_navBarView];
        
        [_navBarView addLeftButtonIcon:@"default_back.png" selecter:@selector(returnVC)];
        
        if (DEBUG_CollectInfo) {
//            [_navBarView addTapCallBack:self sel:@selector(navBarTap)];
        }
    }
    return _navBarView;
}

- (UIView *)statusOrangeView
{
    if (nil == _statusOrangeView) {
        _statusOrangeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, KStatusBarHeight+6)];
        _statusOrangeView.backgroundColor = UIColorFromRGB1(0xFAEEE1);
//        _statusOrangeView.backgroundColor = [UIColor purpleColor];
    }
    return _statusOrangeView;
}
//- (void)navBarTap
//{
//    if (DEBUG_CollectInfo) {
//        DebugResultViewController *d = [[DebugResultViewController alloc]init];
//        EFNavigationController *nav= [[EFNavigationController alloc]initWithRootViewController:d];
//        d.result = self.APPCacheCollectStr ;
//        [self.navigationController presentViewController:nav animated:YES completion:nil];
//    }
//}

- (void)initModel
{
    
}
- (void)initView
{
    //设置导航栏下方不显示内容，此时导航栏无透明度
    //    self.extendedLayoutIncludesOpaqueBars = YES;
    //同时在滚动视图中 设置 属性可以控制滚动内容是否会在bar下方显示。
    self.automaticallyAdjustsScrollViewInsets = NO ;
    //    self.edgesForExtendedLayout = UIRectEdgeNone;
    //    self.modalPresentationCapturesStatusBarAppearance = NO;
    //    self.extendedLayoutIncludesOpaqueBars = NO;
    self.view.backgroundColor = kColorDefultBg;
    
}

- (void)getDataFinish:(BaseModel *)baseModel netError:(NSError *)error
{
    //    [self hideHUD];
    if(error.code == 8){
        [EFShowView showText:@"请先登录！"];
    }else{
        [EFShowView showText:error.domain];
    }
    
    [self handleModelError:baseModel error:error];
}
- (void)handleModelError:(id)sender error:(NSError *)error
{
    [self hideHUD];
    NSString *resul = [NSString stringWithFormat:@"sender = %@ \n error = %@ \n accesstoken = %@\n\n\n",sender,error,[EFAppContext sharedContext].ACCESS_TOKEN];
    EFLog(@"%@",resul);
    
    if (DEBUG_CollectInfo) {
        [self.APPCacheCollectStr appendString:resul];
    }
    
    switch (error.code) {
        case apiErrorCodePsdError:
        {
            EFAppContext *appc = [EFAppContext sharedContext];
            appc.ACCESS_TOKEN = nil ;
            appc.passWard = nil ;
            [appc save];
            
            [self appLogin];
        }break;
        case apiErrorCodeNoLogin:
        {
            EFAppContext *appc = [EFAppContext sharedContext];
            if (!ISEMPTY(appc.userName) && !ISEMPTY(appc.passWard)) {
                [self showHUD];
//                [self.loginModel login:appc.userName passwd:[PublicUtils encode:appc.passWard]];
            }
            else{
                [self appLogin];
            }
        }break ;
        default:
            break;
    }
    
}
- (void)appLogin
{
//    if (![[PublicUtils topViewController] isKindOfClass:[EFLoginViewController class]] ) {
//        
//        QueueStartAfterTime(0.5)
//        EFLoginViewController *login = [[EFLoginViewController alloc]init];
//        EFNavigationController *nav = [[EFNavigationController alloc]initWithRootViewController:login];
//        login.showMessage = @"您没有登录或登录已过期，请重新登录";
//        
//        if (self.navigationController && nav) {
//            [self.navigationController presentViewController:nav animated:YES completion:nil];
//        }
//        else{
//            [EFShowView showInfoText:@"登录已过期，请重新登录"];
//        }
//        queueEnd
//    }
    
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:loginVC animated:YES];
}
- (void)handleSuccess:(id)seder data:(id)data
{
    if (DEBUG_CollectInfo) {
        NSString *result = [NSString stringWithFormat:@"%@ \n %@ \n\n\n",seder,data];
        [self.APPCacheCollectStr appendString:result];
    }
}
//- (void)loginFinished:(BaseResponse *)response
//{
//    //    [EFShowView showInfoView:self.view text:@"加载失败！请重新加载"];
//    
//    EFAppContext *appc = [EFAppContext sharedContext];
//    LoginResponse *loginData = (LoginResponse*)response;
//    appc.ACCESS_TOKEN = loginData.data.access_token;
//    [appc save];
//}

#pragma mark - 返回到前一页
- (void)backWithDelay:(int)delayTime
{
    [self performSelector:@selector(returnVC) withObject:nil afterDelay:delayTime];
}

-(void)returnVC
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 控制器退出键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self bgViewTap];
}
- (void)bgViewTap
{
    [self.view endEditing:YES];
}


#pragma mark -  HUD提示
- (void)showHUD
{
    [self showHUDWithLabel:@""];
}
- (void)showHUDWithLabel:(NSString *)msg
{
    [self hideHUD];
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = msg;
    self.hud.cornerRadius = 5 ;
    [self.hud show:YES];
    self.hud.animationType = MBProgressHUDAnimationZoom ;
    self.hud.opacity = .5 ;
    self.hud.color = [UIColor clearColor];
//    self.hud.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
//    self.hud.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.51];
    self.hud.layer.shadowOpacity = 0.5 ;
    self.hud.layer.shadowOffset = CGSizeMake(0.5, 2);
    self.hud.layer.shadowRadius = 1.5 ;
//    self.hud.layer.shadowColor = kColorDefult.CGColor;
    self.hud.mode = MBProgressHUDModeCustomView;
//    self.hud.labelColor = kColorDefult  ;
    
    //基础父视图
    UIView *hudBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 70, 70)];
    //静止图
//    UIImageView *bgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 70, 70)];
//    bgView.image = [UIImage imageNamed:@"hud_icon"];
//    [hudBgView addSubview:bgView];
//
//    //动态图片
//    UIImageView *imgView =[[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 60, 60)];
    UIImageView *imgView =[[UIImageView alloc] initWithFrame:CGRectMake(18, 18, 30, 30)];
    CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    rotationAnimation.duration = 1.0;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 1000;
    [imgView.layer addAnimation:rotationAnimation forKey:@"position"];
    imgView.image = [UIImage imageNamed:@"hud_loading"];
    [hudBgView addSubview:imgView];
//
    self.hud.customView = hudBgView;
    
    [self bringNavBarToTopmost];
}
- (void)hideHUD
{
    if (self.hud) {
        [self.hud hide:YES afterDelay:0];
        //        [self.hud hideAnimated:YES afterDelay:0];
        self.hud = nil;
    }
}
- (void)hideHUDAfterDelay:(float)delay
{
    if (self.hud) {
        [self.hud hide:YES afterDelay:delay];
        self.hud = nil;
    }
}
- (void)hudWasHidden:(MBProgressHUD *)hud
{
    [hud removeFromSuperview];
}
- (void)showHUDInView:(UIView *)view msg:(NSString *)msg
{
    [self hideHUD];
    self.hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    self.hud.labelText = msg;
    self.hud.animationType = MBProgressHUDAnimationZoom ;
    [self.hud show:YES];
    [self bringNavBarToTopmost];
}
- (void)showHUDInWidownWithMsg:(NSString *)msg
{
    [self hideHUD];
    self.hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    self.hud.labelText = msg;
    self.hud.animationType = MBProgressHUDAnimationZoom ;
    [self.hud show:YES];
    [self bringNavBarToTopmost];
}


#pragma mark - 无网络，无数据 提醒
- (void)showNoDataWithTitle:(NSString *)title
{
    [self showNoDataWithTitle:title inView:self.view];
}
- (void)showNoDataWithTitle:(NSString *)title inView:(UIView *)view
{
    [self hiddenNoDataView];
    
    _nodataView = [EFNoDataView noDataWithTitle:title];
    //    _nodataView.center = view.center ;
    _nodataView.centerX = view.bounds.size.width/2;
    _nodataView.centerY = view.bounds.size.height/2;
    [view addSubview:_nodataView];
}
- (void)showNoDataWithHimg:(NSString *)himg title:(NSString *)title inView:(UIView *)view
{
    [self hiddenNoDataView];
    
    _nodataView = [EFNoDataView noDataWithHimg:himg title:title];
    //    _nodataView.center = view.center ;
    _nodataView.centerX = view.bounds.size.width/2;
    _nodataView.centerY = view.bounds.size.height/2;
    [view addSubview:_nodataView];
    
}
- (void)showNoNetWithDelegate:(id)delegate
{
    [self showNoNetWithDelegate:delegate inView:self.view];
}
- (void)showNoNetWithDelegate:(id)delegate inView:(UIView *)view
{
    [self hiddenNoDataView];
    
    _nodataView = [EFNoDataView noNetViewWithDelegate:delegate];
    _nodataView.center = view.center ;
    [view addSubview:_nodataView];
}
- (void)hiddenNoDataView
{
    if (_nodataView) {
        [_nodataView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [_nodataView removeFromSuperview];
        _nodataView = nil ;
    }
    
}

- (void)alipayWithCode:(NSString *)code
{
    NSAssert(NO, @"支付错误，请重新查看代码!");
}

/**
 * 左边按钮 取消操作 蓝色
 * 右边按钮 确定操作 红色
 *
 * 如果只有一个按钮的话 用sure  cancel为空
 */
- (void)showAlertMessageWithTitle:(NSString *)title contentMessage:(NSString *)contentMessage cancelTitle:(NSString *)cancelTitle cancelCallBack:(allertMessageCallback)cancel sureTitle:(NSString *)sureTitle sureCallBack:(allertMessageCallback)sure
{
    NSAssert(!ISEMPTY(cancelTitle), @"you should add a suretitle and sureCallback");
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:contentMessage preferredStyle:UIAlertControllerStyleAlert];
        
        if (!ISEMPTY(sureTitle)) {
            UIAlertAction *action = [UIAlertAction actionWithTitle:sureTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
                dispatch_after(0.2, dispatch_get_main_queue(), ^{
                    if (sure) sure() ;
                    [alertController dismissViewControllerAnimated:YES completion:nil];
                });
            }];
            [alertController addAction:action];
        }
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            dispatch_after(0.2, dispatch_get_main_queue(), ^{
                if (cancel)  cancel() ;
                [alertController dismissViewControllerAnimated:YES completion:nil];
            });
        }];
        [alertController addAction:action2];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    else{
        
        if (ISEMPTY(sureTitle)) {
            
            _alertMessageCancel = cancel ;
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:title message:contentMessage delegate:self cancelButtonTitle:cancelTitle otherButtonTitles:nil];
            [alertView show];
        }
        else{
            
            _alertMessageSure = sure ;
            _alertMessageCancel = cancel ;
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:title message:contentMessage delegate:self cancelButtonTitle:cancelTitle otherButtonTitles:sureTitle, nil];
            [alertView show];
        }
    }
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        if(_alertMessageCancel) _alertMessageCancel() ;
    }
    else if (buttonIndex == 1){
        if(_alertMessageSure) _alertMessageSure() ;
    }
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDarkContent;
}

#pragma mark - memoryShow
- (void)didReceiveMemoryWarning
{
    EFLog(@"didReceiveMemoryWarning %@\n\n\n\n \n\n\n \n\n\n\n \n\n\n ",self);
    //    NSAssert(NO, @"didReceiveMemoryWarning");
    [super didReceiveMemoryWarning];
    
    if (DEBUG_CollectInfo) {
        [self.APPCacheCollectStr appendFormat:@"didReceiveMemoryWarning %@\n\n",self];
        
        NSString *s = EFUserDefaultsObjForKey(DEBUG_lastCrash);
        NSString *ss = [NSString stringWithFormat:@"%@\n\ndidReceiveMemoryWarning %@",s,self];
        EFUserDefaultsSetObj(ss, DEBUG_lastCrash);
    }
    
    
}
-(void)showMemoryView
{
    NSString *memory = [NSString stringWithFormat:@"系统:%lld,APP:%.0f/%.0f",[self getAvailableMemorySize],[self usedMemory],[self availableMemory]];
    
    UIView *v = [self.view viewWithTag:1321];
    if (v) {
        UILabel *l = (UILabel *)v ;
        l.text = memory ;
    }
    else{
        if (_navBarView) {
            UILabel *l = [[UILabel alloc]initWithFrame:CGRectMake(50, 20, SCREEN_WIDTH-100, 10)];
            l.text = memory;
            l.font = kFontMimi ;
            l.tag = 1321;
            l.textAlignment = NSTextAlignmentCenter ;
            l.textColor = kColorOrange;
            [self.navBarView addSubview:l];
        }
    }
    
}
-(long long)getAvailableMemorySize
{
    vm_statistics_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmStats, &infoCount);
    if (kernReturn != KERN_SUCCESS)
    {
        return NSNotFound;
    }
    
    return ((vm_page_size * vmStats.free_count + vm_page_size * vmStats.inactive_count))/(1024*1024);
}
// 获取当前设备可用内存(单位：MB）
- (double)availableMemory
{
    vm_statistics_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    kern_return_t kernReturn = host_statistics(mach_host_self(),
                                               HOST_VM_INFO,
                                               (host_info_t)&vmStats,
                                               &infoCount);
    
    if (kernReturn != KERN_SUCCESS) {
        return NSNotFound;
    }
    
    return ((vm_page_size *vmStats.free_count) / 1024.0) / 1024.0;
}

// 获取当前任务所占用的内存（单位：MB）
- (double)usedMemory
{
    task_basic_info_data_t taskInfo;
    mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT;
    kern_return_t kernReturn = task_info(mach_task_self(),
                                         TASK_BASIC_INFO,
                                         (task_info_t)&taskInfo,
                                         &infoCount);
    
    if (kernReturn != KERN_SUCCESS
        ) {
        return NSNotFound;
    }
    
    return taskInfo.resident_size / 1024.0 / 1024.0;
}
- (NSMutableString *)APPCacheCollectStr
{
    if (nil == _APPCacheCollectStr) {
        _APPCacheCollectStr  = [NSMutableString string];
    }
    return _APPCacheCollectStr ;
}

//- (EFLoginModel *)loginModel
//{
//    if (nil == _loginModel) {
//        if (nil == _loginHandler) {
//            _loginHandler = [[LoginModelHandler alloc]initWithController:self] ;
//        }
//        _loginModel = [[EFLoginModel alloc]initWithHandler:_loginHandler];
//    }
//    return _loginModel ;
//}
@end


















